<template>
<!-- 收藏模块 -->
   <van-button
      :icon="value ? 'star' : 'star-o'"
      :class="{
         collected: value
      }"
      :loading="loading"
      @click="onCollect"
   />
</template>

<script>
import {
   addCollect,
   deleteCollect
} from '../../api/article'
export default {
   data() {
      return {
         loading: false
      }
   },
   props: {
      value: {
         type: Boolean,
         required: true
      },
      articleId: {
         type: [Number, String, Object],
         required: true
      }
   },
   methods: {
      async onCollect() {
         this.loading = true
         try {
            if (this.value) {
               // 已收藏，取消收藏
               await deleteCollect(this.articleId)
               this.$toast.success('取消收藏')
            } else {
               // 未收藏，添加收藏
               await addCollect(this.articleId)
               this.$toast.success('收藏成功')
            }
            // 更新视图
            this.$emit('input', !this.value)
            // 自定义事件修改数据 并不是立即的  加个 ！ 跟改变的数据一致
            this.$toast.success(
               !this.value ? '收藏成功' : '取消收藏'
            )
         } catch (err) {
            this.$toast.fail('操作失败')
         }
         this.loading = false
      }
   }
}
</script>

<style lang="less" scoped>
.collected {
   .van-icon {
      color: #ffa500;
   }
}
</style>
